package com.tsj.proxy;

import com.tsj.common.Invocation;
import com.tsj.common.URL;
import com.tsj.loadBalance.LoadBalance;
import com.tsj.protocol.HttpClient;
import com.tsj.register.MapRemoteRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @Author tsj
 * @Date 2023/11/15/15:42
 */
public class ProxyFactory {
    public static <T> T  getProxy(Class interfaceClass){
        Object proxyInstance = Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Exception {

                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(), method.getParameterTypes(), args);

                HttpClient httpClient = new HttpClient();
                // 服务发现
                List<URL> urls = MapRemoteRegister.getUrls(interfaceClass.getName());

                // 负载均衡
                URL url = LoadBalance.random(urls);

                // 服务调用
                String result;
                try {
                    result= httpClient.send(url.getHostName(), url.getPort(), invocation);
                }catch (Exception e){
                    // 容错
                    // error_callback
                    result = "报错了";
                }


                return result;
            }
        });
            return (T)proxyInstance;
    }
 }
